import * as React from "react";
import * as monacoGlobal from "monaco-editor";
import SplitPane from "react-split-pane";
import "./SpitEditor.css"; // 假设你有一个单独的 CSS 文件来定义样式

import { EditorPane } from "./EditorPane";
import { GraphPane } from "./GraphPane";
import { SupportedFormat, SupportedEngine } from "../rendering";
import { getSplitConfig, saveSplitConfig } from "../config";

type ErrorList = monacoGlobal.editor.IMarkerData[];

interface Props {
	initialSource: string;
	format: SupportedFormat;
	engine: SupportedEngine;
	onSourceChange?(source: string): void;
}

type State = SourceState | ErroredState;
interface SourceState {
	dotSrc: string;
	errors: undefined;
	lastKnownGoodSrc: undefined;
	showModal: boolean; // 控制弹出层显示/隐藏的状态
	isClickAccept: boolean; // 是否点击同意
	modalMessage: string; // 弹出层的提示信息
}
interface ErroredState {
	dotSrc: undefined;
	errors: ErrorList;
	lastKnownGoodSrc?: string;
	showModal: boolean;
	isClickAccept: boolean; // 是否点击同意
	modalMessage: string;
}

const createSourceState = (dotSrc: string): SourceState => ({
	dotSrc,
	errors: undefined,
	lastKnownGoodSrc: undefined,
	showModal: false,
	isClickAccept: false,
	modalMessage: ""
});
const createErroredState = (
	errors: ErrorList,
	lastKnownGoodSrc?: string
): ErroredState => ({
	dotSrc: undefined,
	errors,
	lastKnownGoodSrc,
	showModal: false,
	isClickAccept: false,
	modalMessage: ""
});
let _dotSrc: any = "graph G {\n" +
	"\t55135 [label=\"35kV迁巩线312开关\" color=\"#FFFF00\" fillcolor=gray fontcolor=black shape=rectangle style=\"bold,filled\"]\n" +
	"\t12240 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t72448 [label=AF_25 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
	"\t12243 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t60135 [label=\"35kV迁巩线31237地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
	"\t12246 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t47979 [label=\"35kV迁巩线3123刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
	"\t12241 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t72449 [label=AF_27 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
	"\t12244 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t60136 [label=\"35kV迁巩线31217地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
	"\t12247 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
	"\t47980 [label=\"35kV迁巩线3121刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
	"\t55135 -- 12240 [color=\"#FFFF00\"]\n" +
	"\t55135 -- 12241 [color=\"#FFFF00\"]\n" +
	"\t12240 -- 72448 [color=\"#FFFF00\"]\n" +
	"\t72448 -- 12243 [color=\"#FFFF00\"]\n" +
	"\t72448 -- 12246 [color=\"#FFFF00\"]\n" +
	"\t12243 -- 60135 [color=\"#FFFF00\"]\n" +
	"\t12246 -- 47979 [color=\"#FFFF00\"]\n" +
	"\t12241 -- 72449 [color=\"#FFFF00\"]\n" +
	"\t72449 -- 12247 [color=\"#FFFF00\"]\n" +
	"\t72449 -- 12244 [color=\"#FFFF00\"]\n" +
	"\t12244 -- 60136 [color=\"#FFFF00\"]\n" +
	"\t12247 -- 47980 [color=\"#FFFF00\"]\n" +
	"}\n";
export default class SplitEditor extends React.Component<Props, State> {
	private editorPaneRef: React.RefObject<EditorPane> = React.createRef();

	constructor(props: Props) {
		super(props);
		const p = this.props;

		this.state = createSourceState(p.initialSource);
		if (p.onSourceChange)
			p.onSourceChange(this.state.dotSrc);
	}

	public loadDotSource(dotSrc: string) {
		const editor = this.editorPaneRef.current;
		if (editor) {
			editor.loadValue(dotSrc);
		}
	}

	dotSourceChanged = (dotSrc: string): void => {
		const p = this.props;
		if (p.onSourceChange)
			p.onSourceChange(dotSrc);

		this.setState(createSourceState(dotSrc));
	};

	dotSourceErrored = (errors: ErrorList): void => {
		this.setState(prevState => {
			const lastKnownGoodSrc = prevState.dotSrc || prevState.lastKnownGoodSrc;
			return createErroredState(errors, lastKnownGoodSrc);
		});
	};

	private getDotSrcToRender() {
		const s = this.state;

		return !!s.dotSrc
			? s.dotSrc
			: s.lastKnownGoodSrc
				? s.lastKnownGoodSrc
				: "";
	}

	private changeNodeValue() {
		const that = this;
		interface ChangeValue {
			oneValue: string, // 鼠标点击第一个值
			twoValue: string, // 鼠标点击第二个值
			isComplete: Boolean // 是否这个已经完成，如果已经完成，就把上面两个值清空
		}
		let changeValue:ChangeValue = { // 改变的值
			oneValue: '', // 鼠标点击第一个值
			twoValue: '', // 鼠标点击第二个值
			isComplete: false // 是否这个已经完成，如果已经完成，就把上面两个值清空
		}
		let oldValue:any = undefined; // 上一次点击的值，防止用户重复点击
		let stepNum:number = 0; //默认0，完成第一个值，就是1

		// const setDotInfoTop = setTimeout(()=>{
		// 	window.clearTimeout(setDotInfoTop);
		// 	that.setState(createSourceState(_dotSrc));
		// },200)
		// 获取所有 class 为 node 的节点
		const clickTimeout = setTimeout( ()=>{
			const nodeElements = document.querySelectorAll('.node');
			window.clearTimeout(clickTimeout)
			// 为每个节点添加点击事件监听器
			nodeElements.forEach((node) => {
				node.addEventListener("click", () => {
					const _dotSrc:any = that.state.dotSrc
					if (stepNum === 2) {
						changeValue.oneValue = "";
						changeValue.twoValue = "";
						stepNum = 0;
					}

					const titleElement = node.querySelector("title");
					if (titleElement) {
						const startValue:any = titleElement.textContent;


						// 将 aa 按行切割并添加 isOpen 属性
						let lines = _dotSrc.split('\n').map((line: any) => ({ line, isOpen: true }));
						let savedEdges:any = [];

						// 构建图
						function buildGraph() {
							const graph:any = {};
							lines.forEach((item: { line: { includes: (arg0: string) => any; split: (arg0: string) => { (): any; new(): any; map: { (arg0: (part: any) => any): [any, any]; new(): any; }; }; }; }) => {
								if (item.line.includes('--')) {
									const [from, to] = item.line.split('--').map(part => part.trim().split(' ')[0]);
									if (!graph[from]) graph[from] = [];
									graph[from].push(to);
								}
							});
							return graph;
						}

						// 深度优先搜索找出相关边
						function dfs(node: string | number, graph: { [x: string]: any[]; }, visited: { has: (arg0: any) => any; add: (arg0: any) => void; }, relevantEdges: string[]) {
							if (visited.has(node)) return;
							visited.add(node);
							if (graph[node]) {
								graph[node].forEach(neighbor => {
									const edge = `${node} -- ${neighbor}`;
									relevantEdges.push(edge);
									dfs(neighbor, graph, visited, relevantEdges);
								});
							}
						}

						const graph = buildGraph();
						const visited = new Set();
						const relevantEdges:any = [];
						dfs(startValue, graph, visited, relevantEdges);

						if (lines.some((item: { line: string | any[]; isOpen: any; }) => relevantEdges.some((edge: string) => item.line.includes(edge)) && item.isOpen)) {
							// 删除相关边
							savedEdges = lines.filter((item: { line: string | any[]; }) => relevantEdges.some((edge: string) => item.line.includes(edge)));
							savedEdges.forEach((item: { isOpen: boolean; }) => item.isOpen = false);
							lines = lines.filter((item: { line: string | any[]; }) => !relevantEdges.some((edge: string) => item.line.includes(edge)));
						} else {
							// 插入相关边
							const closingIndex = lines.findIndex((item: { line: string | string[]; }) => item.line.includes('}'));
							savedEdges.forEach((item: { isOpen: boolean; }) => item.isOpen = true);
							lines.splice(closingIndex, 0, ...savedEdges);
						}

						const newGraph = lines.map((item: { line: any; }) => item.line).join('\n');

						debugger;

						const setDotInfo = setTimeout(()=>{
							window.clearTimeout(setDotInfo);
							that.setState(createSourceState(""));
							that.setState(createSourceState(newGraph));
							const changeB = setTimeout(() => {
								window.clearTimeout(changeB);
								that.changeNodeValue();
							}, 200);

						},1800)


						// return
						// if (titleValue!== oldValue) {
						// 	if (stepNum === 0) {
						// 		if (typeof titleValue === "string") {
						// 			changeValue.oneValue = titleValue;
						// 			oldValue = titleValue;
						// 			stepNum = 1;
						// 		}
						// 		// 显示弹出层并设置提示信息
						// 		that.setState({
						// 			showModal: true,
						// 			modalMessage: `${changeValue.oneValue} 设定为【起始线】成功`
						// 		});
						// 		const setDotInfoOne = setTimeout(()=>{
						// 			window.clearTimeout(setDotInfoOne);
						// 			that.setState({showModal: false})
						// 		},1800)
						// 	} else if (stepNum === 1) {
						// 		if (typeof titleValue === "string") {
						// 			changeValue.twoValue = titleValue;
						// 			oldValue = titleValue;
						// 			stepNum = 2;
						// 		}
						// 		let _dotSrc: any = "graph G {\n" +
						// 			"\t55135 [label=\"35kV迁巩线312开关\" color=\"#FFFF00\" fillcolor=gray fontcolor=black shape=rectangle style=\"bold,filled\"]\n" +
						// 			"\t12240 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t72448 [label=AF_25 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
						// 			"\t12243 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t60135 [label=\"35kV迁巩线31237地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
						// 			"\t12246 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t47979 [label=\"35kV迁巩线3123刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
						// 			"\t12241 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t72449 [label=AF_27 color=\"#FFFF00\" fixedsize=true height=0.2 shape=circle style=dashed width=0.2]\n" +
						// 			"\t12244 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t60136 [label=\"35kV迁巩线31217地刀\" color=\"#FFFF00\" fontcolor=gray shape=rectangle]\n" +
						// 			"\t12247 [label=\"\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fixedsize=true height=0.1 shape=circle style=filled width=0.1]\n" +
						// 			"\t47980 [label=\"35kV迁巩线3121刀闸\" color=\"#FFFF00\" fillcolor=\"#FFFF00\" fontcolor=white shape=rectangle style=\"bold,filled\"]\n" +
						// 			"\t55135 -- 12240 [color=\"#FFFF00\"]\n" +
						// 			"\t55135 -- 12241 [color=\"#FFFF00\"]\n" +
						// 			"\t12240 -- 72448 [color=\"#FFFF00\"]\n" +
						// 			"\t72448 -- 12243 [color=\"#FFFF00\"]\n" +
						// 			"\t72448 -- 12246 [color=\"#FFFF00\"]\n" +
						// 			"\t12243 -- 60135 [color=\"#FFFF00\"]\n" +
						// 			"\t12246 -- 47979 [color=\"#FFFF00\"]\n" +
						// 			"\t12241 -- 72449 [color=\"#FFFF00\"]\n" +
						// 			"\t72449 -- 12247 [color=\"#FFFF00\"]\n" +
						// 			"\t72449 -- 12244 [color=\"#FFFF00\"]\n" +
						// 			"\t12244 -- 60136 [color=\"#FFFF00\"]\n" +
						// 			"\t12247 -- 47980 [color=\"#FFFF00\"]\n" +
						// 			"}\n";
						// 		// let _dotSrc: any = that.state.dotSrc;
						// 		const colorRegex = /color="([^"]+)"/;
						// 		const match = _dotSrc.match(colorRegex);
						// 		let color;
						// 		if (match) {
						// 			color = match[1];
						// 		} else {
						// 			color = "#000000";
						// 		}
						//
						// 		// 构建新的边信息
						// 		const newEdge = `\t${changeValue.oneValue} -- ${changeValue.twoValue} [color="${color}"]\n`;
						//
						// 		// 在 dotSrc 字符串的倒数第二个字符（即 '}' 之前）插入新的边信息
						// 		_dotSrc = _dotSrc.slice(0, -2) + newEdge + _dotSrc.slice(-2);
						//
						// 		// debugger
						// 		// 显示弹出层并设置提示信息
						// 		that.setState({
						// 			showModal: true,
						// 			modalMessage: `${changeValue.twoValue} 设定为【终止线】成功`
						// 		});
						//
						// 		const setDotInfo = setTimeout(()=>{
						// 			window.clearTimeout(setDotInfo);
						// 			that.setState(createSourceState(""));
						// 			that.setState(createSourceState(_dotSrc));
						//
						// 			const changeB = setTimeout(() => {
						// 				window.clearTimeout(changeB);
						// 				that.changeNodeValue();
						// 			}, 200);
						// 		},1800)
						//
						//
						// 	}
						// }
					}
					console.log(changeValue);
				});
			});
		}, 1000);
	}

	public componentDidMount() {
		this.changeNodeValue();
		window.localStorage.setItem('_dotSrc', _dotSrc) //先存一次
		this.setState(createSourceState(_dotSrc));
	}

	// 关闭弹出层的方法
	closeModal = () => {
		this.setState({ showModal: false });
		this.setState({ isClickAccept: false });
	};

	// 取消按钮的点击处理方法
	handleCancel = () => {
		this.closeModal();
		this.setState({ isClickAccept: false });
	};

	// 确定按钮的点击处理方法
	handleConfirm = () => {
		this.closeModal();
		this.setState({ isClickAccept: true });
		// 这里可以添加确定按钮的其他逻辑
	};

	public render() {
		const s = this.state;
		const p = this.props;
		const that = this;

		const isErrored = s.errors && s.errors.length > 0;
		const dotSrc = this.getDotSrcToRender();

		console.log("dotSrcsssss");
		console.log(dotSrc);

		var messageHandle = function (e: any) {
			let dotSrc = e.data
			console.log("接受到的信息是：" + e.data);
			let dotSrc22 = encodeURIComponent(`"# Place the cursor inside "graph" to get some refactoring options

      graph {

        # To refactor nodes, place the cursor left to a node name
        a -- b
        a -- c;
        a -- d;
        a -- b;
        a -- ec;

        # Hover over color names to get a color picker
        b -- b [color=blue]
        b -- d [color="#ff0000"];

        # Get completion when assigning a shape or color
        b [shape=box, color=yellow];

        a; # You can remove optional ; by placing the cursor left to a semicolon
      }
      "`);
			that.setState(createSourceState(dotSrc));
			that.changeNodeValue();
		};

		if (window.addEventListener) {
			window.addEventListener("message", messageHandle, false);
		}

		console.log("this.state.dotSrc", dotSrc);
		console.log("this.state.dotSrc", s.dotSrc);

		const graphPaneClass = isErrored? "errored" : "successful";

		return (
			<div>
				<SplitPane
					split="vertical"
					minSize={50}
					defaultSize={getSplitConfig() || "50%"}
					onChange={size => saveSplitConfig(size)}
				>
					<EditorPane
						ref={this.editorPaneRef}
						defaultValue={s.dotSrc}
						onChangeValue={this.dotSourceChanged}
						onValueError={this.dotSourceErrored}
					/>
					<GraphPane
						className={"graph-container " + graphPaneClass}
						dotSrc={dotSrc}
						engine={p.engine}
						format={p.format}
					/>
				</SplitPane>
				{/* 弹出层 */}
				{s.showModal && (
					<div className="modal-overlay">
						<div className="modal">
							<div className="modal-header">
								<span className="modal-title">提示</span>
								{/*<span className="close-button" onClick={this.closeModal}>&times;</span>*/}
							</div>
							<div className="modal-body">{s.modalMessage}</div>
							{/*<div className="modal-footer">*/}
							{/*	<button className="cancel-button" onClick={this.handleCancel}>*/}
							{/*		取消*/}
							{/*	</button>*/}
							{/*	<button className="confirm-button" onClick={this.handleConfirm}>*/}
							{/*		确定*/}
							{/*	</button>*/}
							{/*</div>*/}
						</div>
					</div>
				)}
			</div>
		);
	}
}
